package gajdulewiczr;

import java.util.Random;

public class TerrainProvider {

	private float a = 0, b = 1;

	static Random r = new Random();
	int xseed = r.nextInt();
	int yseed = r.nextInt();

	public float[][] nextTerrain() {
		xseed = r.nextInt();
		yseed = r.nextInt();
		return smooth(newPerlin(128));
	}

	private float[][] smooth(float[][] np) {
		int size = np.length;
		float corners, sides, center;
		for (int i = 1; i < size - 1; i++) {
			for (int j = 1; j < size - 1; j++) {
				corners = (np[i + 1][j + 1] + np[i - 1][j - 1]
						+ np[i - 1][j + 1] + np[i + 1][j - 1]) / 4;
				sides = (np[i][j + 1] + np[i + 1][j] + np[i - 1][j] + np[i][j - 1]) / 8;
				center = np[i][j] / 4;
				np[i][j] = cos_inter(corners + sides + center);
			}
		}
		return np;
	}

	private float cos_inter(float x) {
		float ft = x * 3.1415927f;
		float f = (float) (1 - Math.cos(ft)) * .5f;

		return a * (1 - f) + b * f;
	}

	private float[][] newPerlin(int size) {
		float[][] ret = new float[size][size];
		for (int i = 1; i < size - 1; i++) {
			for (int j = 1; j < size - 1; j++) {
				ret[i][j] = perlin2(i, j);
			}
		}
		return ret;
	}

	private float perlin2(int x, int y) {
		x += xseed;
		y += yseed;
		x += y * 47;
		x = (x << 13) ^ x;
		return (1.0f - ((x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) * 0.000000000931322574615478515625f);
	}
}
